package com.itheima.web.controller.front;

import com.itheima.domain.front.Member;
import com.itheima.web.controller.BaseServlet;
import com.itheima.web.controller.Code;
import com.itheima.web.controller.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: mm_exam
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-18 20:16
 **/
@WebServlet("/member/*")
public class MemberServlet extends BaseServlet {
    public Result register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Member data = getData(req, Member.class);
        //调用逻辑层api
        boolean flag = memberService.register(data);
        Result result;
        if (flag) {
            result = new Result("注册成功", null);
        } else {
            result = new Result("注册失败", null);
        }
        return result;

    }

    public Result logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        boolean flag = memberService.logout(id);
        if (flag) {

            return new Result("退成成功!", flag);
        } else {

            return new Result(Code.LOGOUT_FAIL, flag, false, "");
        }
    }

    public Result checkLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
        Member member = getData(req, Member.class);
        //获取到的id到redis中查询,是否存在
        String nickName = memberService.getLoginInfo(member.getId());
        return new Result("", nickName);
    }

    public Result login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Member data = getData(req, Member.class);
        //调用逻辑层api
        Member member = memberService.login(data.getEmail(), data.getPassword());
        Result result;
        if (member != null) {
            result = new Result("登录成功", member);
        } else {
            //Integer code, Object data, boolean flag, String message
            result = new Result(Code.LOGIN_FAIL, null, false, "用户名或者密码错误,请重试!");
        }
        return result;

    }

}
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//     //收集数据
//     Member json = JSON.parseObject(req.getInputStream(), Member.class);
//     System.out.println(json);
//     //    组织成一个实体类
//
//     //调用逻辑层api
//     boolean flag = memberService.register(json);
//     Result result = null;
//     if (flag) {
//         result = new Result("注册成功", null);
//     } else {
//         result = new Result("注册失败", null);
//     }
//     //返回结果
//     resp.setContentType("application/json;charset=utf-8");
//     JSON.writeJSONString(resp.getOutputStream(), result);
// }